/*


log2mongo :: Logs messages to MongoDB
__________________________________________

Copyright (c) 2011 Gaurav Kumar, Pivotal Security LLC

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#include <cstdlib>
#include <iostream>
#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include "client/dbclient.h"
#include "bson/oid.h"
#include "SimpleIni.h"
#include "hostandport.h"


using boost::asio::ip::udp;
using namespace mongo;
class server
{

public:
  server(boost::asio::io_service& io_service, short port,const char * dbhost)
    : io_service_(io_service),
      socket_(io_service, udp::endpoint(udp::v4(), port))
  {
      ctr=0;
	  hp=string(dbhost);
     try{
        using namespace mongo;
          mConn = new mongo::DBClientConnection(true,NULL,NULL );
          mConn->connect(hp);
          //if(mConn->auth("db","user","pass",err,false)){  }


      }
      catch( DBException &e ) {
      cout << "Exception while creating DB Connection object: " << e.what() << endl;
      exit(1);
      }
    socket_.async_receive_from(boost::asio::buffer(data_, max_length), sender_endpoint_, boost::bind(&server::handle_receive_from, this,boost::asio::placeholders::error,          boost::asio::placeholders::bytes_transferred));
  }

  void handle_receive_from(const boost::system::error_code& error,
      size_t bytes_recvd)
  {

    if (!error && bytes_recvd > 0)
    {
	  server::handle_send_to(mConn,bytes_recvd);
    }
    else
    {
      socket_.async_receive_from(boost::asio::buffer(data_, max_length), sender_endpoint_,boost::bind(&server::handle_receive_from, this,boost::asio::placeholders::error,boost::asio::placeholders::bytes_transferred));
    }
  }

  void handle_send_to(mongo::DBClientConnection* conn,size_t len)
  {


    std::string data(data_,len);
    BSONObjBuilder b;
    b.append("logString", data);
    BSONObj p = b.obj();

        try{
            conn->insert("inbox.Logs",p);
            ctr++;
            cout<<"Log sent to database. Counter= "<<ctr<<" data= "<<data<<endl;

            } catch (std::exception& e)
              {
                  std::cerr << "Exception occurred while inserting log: " << e.what() << "\n";
                  std::cerr << "log data: "<<data<<endl;

              }


    socket_.async_receive_from(boost::asio::buffer(data_, max_length), sender_endpoint_,boost::bind(&server::handle_receive_from, this,boost::asio::placeholders::error,boost::asio::placeholders::bytes_transferred));
  }

private:
  boost::asio::io_service& io_service_;
  udp::socket socket_;
  udp::endpoint sender_endpoint_;
  enum { max_length = 1024 };
  char data_[max_length];
  long int ctr;
  mongo::DBClientConnection* mConn;
  bool auth;
  HostAndPort hp;
  string err;

};


extern "C"
int main(int argc, char* argv[])
{

using namespace std;
using namespace mongo;

 try
  {

	cout<<"log2mongo :: Logs messages to MongoDB"<<endl;
	cout<<"Version 0.1"<<endl;
	cout<<"Copyright (c) 2011 Gaurav Kumar, Pivotal Security LLC"<<endl;
	cout<<endl;
	cout<<"Usage: ./logger"<<endl;
	cout<<"config.ini file must be in same directory from where you are running ./logger"<<endl;
	cout<<endl;
	cout<<endl;
    CSimpleIniA ini;
    ini.SetUnicode();
    SI_Error rc;
    rc= ini.LoadFile("config.ini");

    if(rc<0){std::cerr<<"!!!  config.ini not found in current directory. Proceeding with defaults.   !!!"<<endl<<endl;;
    } else {
    	cout<<"config.ini has been read"<<endl<<endl;
    }


    const char * pVal = ini.GetValue("logger", "port", "514");
    const char * dbhost = ini.GetValue("db", "host:port", "localhost:27017");
    cout<<"Going to listen on port "<<pVal<<endl;
    cout<<"Going to use MongoDB instance running on "<<dbhost<<endl;
    boost::asio::io_service io_service;
    server s(io_service, atoi(pVal),dbhost);
    cout<<"Now ready to accept messages..."<<endl;
    io_service.run();
  }
  catch (std::exception& e)
  {
    std::cerr << "Exception found: " << e.what() << "\n";
  }

  return 0;
}
